package me.seu.demo.common.ftp;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpMode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * ftp 工具类
 *
 * @author: liangfeihu
 * @since: 2024-11-20 13:38
 */
@Slf4j
public class XcFtpUtil {

    private static final String FTP_USERNAME = "ftpuser";
    private static final String FTP_PASSWORD = "1JDProd078JIHibif2b2ibgi2u93o";
    private static final String FTP_HOST = "114.67.101.200";
    private static final int FTP_PORT = 221;

    public static void main(String[] args) {
        Ftp ftp = getFTPClient();

        Date startTime = DateUtil.parse("2024-11-20 09:44:54");
        String dateStr = DateUtil.format(startTime, DatePattern.PURE_DATE_PATTERN);
        String timeStr = DateUtil.format(startTime, DatePattern.PURE_TIME_PATTERN);

        String dateStr2 = DateUtil.format(startTime, "yyyy_MM_dd");
        String timeStr2 = DateUtil.format(startTime, "HH_mm_ss");

        log.info("dateStr2={} timeStr2={} ", dateStr2, timeStr2);

        String fileName = "";
        String oldFileName = "";
        String path = "/hk_file/20241120";
        if (path.startsWith("/")) {
            path = path.substring(1);
        }
        try {
            FTPFile[] ftpFiles = ftp.lsFiles(path);
            for (int i = 0; i < ftpFiles.length; i++) {
                FTPFile ftpFile = ftpFiles[i];
                if (ftpFile.isFile()) {
                    String name = ftpFile.getName();
                    log.info("文件名：{}", name);
                    if (name.contains(dateStr) && name.contains(timeStr)) {
                        fileName = name;
                        log.info("文件名2：{}", name);
                        break;
                    } else if (name.contains(dateStr2) && name.contains(timeStr2)) {
                        oldFileName = name;
                        log.info("文件名3：{}", name);
                        fileName = name.substring(name.indexOf("_") + 1);
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("遍历某个目录下所有文件异常", e);
        } finally {
            //关闭连接
            try {
                if (ftp != null) ftp.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (StringUtils.isNotBlank(oldFileName)) {
            renameFile(path, oldFileName, fileName);
        }
    }


    public static void renameFile(String path, String oldFileName, String fileName) {
        try {
            Ftp ftp = getFTPClient();
            ftp.cd(path);
            FTPClient client = ftp.getClient();
            boolean renameFlag = client.rename(oldFileName, fileName);
            log.info("文件重命名：{} {}", oldFileName, fileName);
            log.info("文件重命名：path={} renameFlag={} ", path, renameFlag);

            if (renameFlag) {
                log.info("文件重命名成功");
            } else {
                log.info("文件重命名失败");
                boolean delFlag = delFile(path, oldFileName);
                log.info("删除文件：{} {}", oldFileName, delFlag);
            }
        } catch (IOException e) {
            log.error("文件名重命名：{} rename异常", fileName, e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除FTP服务器中的文件
     *
     * @param remoteFile ftp上的文件路径
     */
    public static boolean delFile(String path, String remoteFile) {
        if (StringUtils.isBlank(remoteFile)) {
            return false;
        }

        Ftp ftp = getFTPClient();
        try {
            ftp.cd(path);
            return ftp.delFile(remoteFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除FTP服务器中的文件异常", e);
            return false;
        } finally {
            //关闭连接
            try {
                if (ftp != null) ftp.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static Ftp getFTPClient() {
        try {
            Ftp ftp = new Ftp(FTP_HOST, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, CharsetUtil.CHARSET_ISO_8859_1);
            //设置为被动模式，防止防火墙拦截
            ftp.setMode(FtpMode.Passive);

            log.info("获取ftp客户端成功");
            return ftp;
        } catch (Exception e) {
            log.error("获取ftp客户端异常", e);
            throw new RuntimeException("获取ftp客户端异常:" + e.getMessage());
        }
    }

}
